from PySide6.QtCore import Signal, Slot
from PySide6.QtWidgets import QDialog
from Forms.DownloadDialogForm import DownloadDialogForm
from Libs import Excel
from . import *
import time


class ExportDataDialog(QDialog):
    download = Signal(dict)
    closeSignal = Signal()

    def __init__(self, parentWidget=None):
        super().__init__()

        self.parentWidgets = parentWidget
        self.mainUi = DownloadDialogForm()
        self.mainUi.setupUi(self)

        if self.parentWidgets.contactMode == 1:
            self.mainUi.contactModeMobile.setChecked(True)
        elif self.parentWidgets.contactMode == 2:
            self.mainUi.contactModeWechat.setChecked(True)
        else:
            self.mainUi.contactModeAll.setChecked(True)
        self.time = int(time.time())

        excelPath = f"./{setting.get('excelPath')}/{setting.get('excelFileName')}_{str(self.time)}.xlsx"
        self.mainUi.filePathLineEditor.setText(excelPath)
        self.mainUi.filePathLineEditor.setEnabled(False)

        self.downloadBody = {
            'start_date': 0,
            'end_date': 0,
            'contact_mode': 0
        }
        self.downloadRes = []

        self.mainUi.cancelButton.clicked.connect(self.closeDialog)
        self.mainUi.downloadButton.clicked.connect(self.downloadData)

    def setDownloadBody(self):
        if self.mainUi.contactModeMobile.isChecked():
            self.downloadBody['contact_mode'] = 1
        elif self.mainUi.contactModeWechat.isChecked():
            self.downloadBody['contact_mode'] = 2
        else:
            self.downloadBody['contact_mode'] = 0
        
        self.downloadBody['start_date'] = self.mainUi.startDate.text()
        self.downloadBody['end_date'] = self.mainUi.endDate.text()

    def closeDialog(self):
        self.closeSignal.emit()

    def downloadData(self):
        self.setDownloadBody()
        self.download.emit(self.downloadBody)
        self.mainUi.downloadButton.setEnabled(False)

    @Slot(dict)
    def updateDownloadProgress(self, data):
        value = data.get('progress', 0.0)
        downloadData = data.get('data', [])
        self.mainUi.downloadProgress.setValue(value)
        arr = []
        for x in downloadData:
            arr.append([
                x.get('created_at'),
                x.get('uid'),
                x.get('nickname'),
                x.get('tag'),
                x.get('mobile'),
                x.get('wechat'),
                x.get('dy_id'),
                x.get('fans_num'),
                '采集到手机号码' if x.get('contact_status') == 2 else ('采集不到手机号码' if x.get('contact_status') == 1 else '还没采集过手机号码'),
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x.get('mobile_updated_at'))) if x.get('mobile_updated_at') != 0 else '',
            ])
        self.downloadRes.extend(arr)
        logging.debug(f'downloadRes length: {len(self.downloadRes)}')
        if value == 100:
            # 接口调用完毕100%, 准备下载文件
            self.mainUi.downloadButton.setEnabled(True)
            self.data2Excel()

    def data2Excel(self):
        logging.debug(f'准备写入excel的数据: {self.downloadRes}')
        if not self.downloadRes:
            return False
        Excel.do_export_excel(path='template.xlsx', export_file='', data_array=self.downloadRes, file_suffix=str(self.time))
        
